//
//  ScrumEditView.swift
//  codelabs
//
//  Created by 雷雷 on 25/05/2025.
//

import SwiftUI
import SwiftData
import ThemeKit

struct ScrumEditor: View {
    let scrum:DailyScrum
    
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var context
    
    @State private var errorWrapper:ErrorWrapper?
    
    @State private var attendeeName:String = ""
    
    @State var title:String
    @State private var lengthInMinutesAsDouble:Double
    @State private var attendees:[Attendee]
    @State var theme:Theme
    
    private let isCreateAction:Bool
    
    init(_ scrum:DailyScrum? = nil){
        let scrumToEdit:DailyScrum
        if let scrum {
            isCreateAction=false
            scrumToEdit=scrum
        }else{
            isCreateAction=true
            scrumToEdit=DailyScrum(theme:.sky)
        }
        self.scrum=scrumToEdit
        
        self.title=self.scrum.title
        self.lengthInMinutesAsDouble=self.scrum.lengthInMinutesAsDouble
        self.attendees=self.scrum.attendees
        self.theme=self.scrum.theme
    }
    
    var body: some View {
        List{
            Section(header:Text("Meeting Info")){
                TextField("Title",text:$title)
                    .frame(maxWidth:.infinity)
                
                HStack{
                    Slider(value: $lengthInMinutesAsDouble,in: 5...30,step:1)
                        .accessibilityValue("\(String(format:"%.0f",lengthInMinutesAsDouble)) minutes")
                    
                    Spacer()
                    
                    Text("\(String(format:"%.0f",lengthInMinutesAsDouble)) min")
                        .accessibilityHidden(true)
                }.padding(.vertical)
                
                Spacer()
                
                ThemePicker(selected:$theme)
            }
            
            
            Section(header:Text("Attendees")){
                ForEach(attendees){attendee in
                    Label(attendee.name,systemImage:"person")
                        .font(.headline)
                        .padding(.vertical,6)
                }
                .onDelete{ indicies in
                    attendees.remove(atOffsets: indicies)
                }
                
                HStack{
                    TextField("New Attendee",text:$attendeeName)
                        .onSubmit {
                            appendAttendee()
                        }
                    
                    Spacer()
                    
                    Button(action:{
                        appendAttendee()
                    }){
                        Image(systemName:"plus.circle.fill")
                            .accessibilityLabel("Add attendee")
                    }
                    .disabled(attendeeName.isEmpty)
                }
                .padding(.vertical)
            }
        }
        .navigationTitle(title)
        .toolbar{
            ToolbarItem(placement:.cancellationAction){
                Button(action:{
                    dismiss()
                }){
                    Text("Cancel")
                }
            }
            
            ToolbarItem(placement:.confirmationAction){
                Button(action:{
                    do{
                        try saveOrUpdate()
                        dismiss()
                    }catch{
                        errorWrapper = ErrorWrapper(error: error, guidance: "Daily scrum was not recorded. Try again later.")
                    }
                }){
                    Text("Done")
                }
            }
        }
        .sheet(item: $errorWrapper) {
            dismiss()
        } content: { wrapper in
            ErrorView(errorWrapper: wrapper)
        }
    }
    
    func saveOrUpdate() throws{
        scrum.title=self.title
        scrum.lengthInMinutes=Int(self.lengthInMinutesAsDouble)
        scrum.attendees=self.attendees
        scrum.theme=self.theme
        
        if isCreateAction{
            context.insert(scrum)
        }else{
            try context.save()
        }
    }
    
    func appendAttendee(){
        withAnimation(.spring(duration:0.28)){
            attendees.append(Attendee(name: attendeeName))
            attendeeName=""
        }
    }
}

#Preview(traits:.dailyScrumSampleData) {
    @Previewable @Query(sort:\DailyScrum.title) var scrums:[DailyScrum]
    
    @Previewable @State var errorWrapper:ErrorWrapper? = ErrorWrapper(
        error:SampleError.errorRequired,
        guidance: "HHH"
    )
    
    NavigationStack{
        ScrumEditor(scrums[0])
        
    }
}
